package com.alibaba.nacos.naming.remote.rpc.handler;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.api.remote.response.ResponseCode;
import com.alibaba.nacos.consistency.DataOperation;
import com.alibaba.nacos.core.distributed.distro.DistroProtocol;
import com.alibaba.nacos.core.distributed.distro.component.DistroDataProcessor;
import com.alibaba.nacos.core.distributed.distro.entity.DistroData;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.naming.cluster.remote.request.DistroDataRequest;
import com.alibaba.nacos.naming.cluster.remote.response.DistroDataResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DistroDataRequestHandler
        extends RequestHandler<DistroDataRequest, DistroDataResponse> {

    /**
     * @see com.alibaba.nacos.naming.consistency.ephemeral.distro.v2.DistroClientDataProcessor
     */
    @Autowired
    private DistroDataProcessor distroDataProcessor;

    @Override
    public DistroDataResponse handle(DistroDataRequest request,
                                     RequestMeta meta) throws NacosException {
        DataOperation dataOperation = request.getDataOperation();
        switch (dataOperation) {
            case VERIFY -> {
                return null;
            }
            case SNAPSHOT -> {
                return null;
            }
            case ADD, CHANGE, DELETE -> {
                return handleSynData(request.getDistroData());
            }
            case QUERY -> {
                return null;
            }
            default -> {
                return new DistroDataResponse();
            }
        }
    }

    private DistroDataResponse handleSynData(DistroData distroData) {
        DistroDataResponse response = new DistroDataResponse();
        boolean b = distroDataProcessor.processData(distroData);
        if (!b) {
            response.setErrorCode(ResponseCode.FAIL.getCode());
            response.setMessage("distro data processing failed");
        }
        return response;
    }
}

